package com.cango.student.lthread;

import java.util.concurrent.atomic.AtomicBoolean;


/**
 * 交替打印奇偶数
 */
public class TwoThread2 {

    public int start = 1;

    /**
     * 用 AtomicBoolean
     */
    public AtomicBoolean flag = new AtomicBoolean(true);

    public static void main(String[] args) {
        TwoThread2 twoThread = new TwoThread2();

        Thread t1 = new Thread(new OuNum(twoThread));
        t1.setName("t1");


        Thread t2 = new Thread(new JiNum(twoThread));
        t2.setName("t2");

        t1.start();
        t2.start();
    }

    /**
     * 偶数线程
     */
    public static class OuNum implements Runnable {

        private TwoThread2 number;

        public OuNum(TwoThread2 number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <= 100) {
                // 用cas保证其原子性
                if (number.flag.compareAndSet(true, false)) {
                    System.out.println(Thread.currentThread().getName() + "+-+" + number.start);
                    number.start++;
                } else {
                    try {
                        //防止线程空转
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 奇数线程
     */
    public static class JiNum implements Runnable {

        private TwoThread2 number;

        public JiNum(TwoThread2 number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start <= 100) {
                // 用cas保证其原子性
                if (number.flag.compareAndSet(false, true)) {
                    System.out.println(Thread.currentThread().getName() + "+-+" + number.start);
                    number.start++;
                } else {
                    try {
                        //防止线程空转
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
